package com.admin.common.utils;

import com.admin.common.entity.CaptchaParamConfigBO;
import com.admin.common.enums.LoginCodeEnum;
import com.admin.common.exception.BadConfigurationException;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;

import java.awt.*;

/**
 * 验证码工具
 *
 * @author sq-lan
 */
public class CaptchaUtil {

    public static Captcha create(CaptchaParamConfigBO config) {
        Captcha captcha;
        if (LoginCodeEnum.ARITHMETIC.getCode().equals(config.getType())) {
            // 算术类型 https://gitee.com/whvse/EasyCaptcha
            captcha = new FixedArithmeticCaptcha(config.getWidth(), config.getHeight());
        } else if (LoginCodeEnum.CHINESE.getCode().equals(config.getType())) {
            captcha = new ChineseCaptcha(config.getWidth(), config.getHeight());
        } else if (LoginCodeEnum.CHINESE_GIF.getCode().equals(config.getType())) {
            captcha = new ChineseGifCaptcha(config.getWidth(), config.getHeight());
        } else if (LoginCodeEnum.GIF.getCode().equals(config.getType())) {
            captcha = new GifCaptcha(config.getWidth(), config.getHeight());
        } else if (LoginCodeEnum.SPEC.getCode().equals(config.getType())) {
            captcha = new SpecCaptcha(config.getWidth(), config.getHeight());
        } else {
            throw new BadConfigurationException("验证码配置信息错误,正确配置查看 LoginCodeEnum ");
        }
        captcha.setLen(config.getLength());

        if (StringUtils.isNotBlank(config.getFontName())) {
            captcha.setFont(new Font(config.getFontName(), Font.PLAIN, config.getFontSize()));
        }
        return captcha;
    }

    static class FixedArithmeticCaptcha extends ArithmeticCaptcha {
        public FixedArithmeticCaptcha(int width, int height) {
            super(width, height);
        }

        @Override
        protected char[] alphas() {
            // 生成随机数字和运算符
            int n1 = num(1, 10), n2 = num(1, 10);
            int opt = num(3);

            // 计算结果
            int res = new int[]{n1 + n2, n1 - n2, n1 * n2}[opt];
            // 转换为字符运算符
            char optChar = "+-x".charAt(opt);

            this.setArithmeticString(String.format("%s%c%s=?", n1, optChar, n2));
            this.chars = String.valueOf(res);

            return chars.toCharArray();
        }
    }
}
